<?php

namespace App\Traits;

use App\Enums\RedisKeyEnum;
use App\Enums\ContentNameEnum;
use App\Exceptions\BasicException;
use App\Services\Tools\HelperService;

trait UserAction
{
    //判断用户是否拥有某行为的权限,返回true拥有,false无
    public function haveUserActionAuth($user_id, $action_id)
    {
        $result = $this->getUserActionAuth($user_id);
        if (isset($result[$action_id]) && ($result[$action_id] == -1 || $result[$action_id] > time())) {
            return false;
        }
        return true;
    }
    //获取用户的行为列表
    public function getUserActionAuth($user_id)
    {
        $key = sprintf(RedisKeyEnum::USER_ACTION, $user_id);
        if (!app('redis')->exists($key)) {
            $user_action = app('model_user_action_banned')->getUserAction($user_id);
            $set_data = [0 => 0];
            if (isset($user_action->banned_action)) {
                $set_data_decode = json_decode($user_action->banned_action, true);
                if ($set_data_decode && is_array($set_data_decode)) {
                    $set_data = $set_data_decode;
                }
            }
            app('redis')->hmset($key, $set_data);
            app('redis')->expire($key, 604800);
            $result = $set_data;
        } else {
            $result = app('redis')->hgetall($key);
        }
        return $result;
    }
    //判断用户是否拥有某行为的权限,如果无权限,直接抛出异常
    public function checkUserAction($user_id, $action_id)
    {
        $result = $this->getUserActionAuth($user_id);
        if (isset($result[$action_id]) && ($result[$action_id] == -1 || $result[$action_id] > time())) {
            if ($result[$action_id] == -1) {
                $expire_time = '永久';
            } else {
                $expire_time = HelperService::time_format($result[$action_id] - time());
            }
            $this->throw_error($action_id, ['time' => $expire_time]);
        }
    }

    public function throw_error($action_id, $params = [])
    {
        switch ($action_id) {
            case ContentNameEnum::PRIVATE_CHAT;
                throw new BasicException(46002, '', $params);
            case ContentNameEnum::CHAT_SQUARE;
                throw new BasicException(46003, '', $params);
            case ContentNameEnum::MICROBLOG;
                throw new BasicException(46004, '', $params);
            default:
                throw new BasicException(46001, '', $params);
        }
    }
}
